package com.shr.xsunmvc;

import java.lang.reflect.Method;

import com.shr.xsunmvc.config.ConfigLoader;
import com.shr.xsunmvc.render.JspRender;
import com.shr.xsunmvc.render.Render;
import com.shr.xsunmvc.route.Routers;
import com.shr.xsunmvc.servlet.packer.Request;
import com.shr.xsunmvc.servlet.packer.Response;

/**
 * Xsun 全局类
 * 内部静态类单例模式
 * @author sun haoran
 *
 */
public final class Xsun {
	/**
	 * 存放所有的路由
	 */
	private Routers routers ;
	
	/**
	 * 配置加载器
	 */
	private ConfigLoader configLoader ;
	
	/**
	 * 框架是否已经初始化
	 */
	private boolean init = false;
	
	
	/**
	 * 渲染器
	 */
	private Render render ;
	
	private Xsun(){
		routers = new Routers() ;
		configLoader = new ConfigLoader() ;
		render = new JspRender() ;
	}
	
	public boolean isInit(){
		return init ;
	}
	
	public void setInit(boolean init){
		this.init = init ;
	}
	/**
	 * 静态内部类单例模式
	 * @author sun haoran
	 *
	 */
	private static class XsunHolder{
		private static Xsun ME  = new Xsun();
	}
	/**
	 * 
	 * @return 单例的Xsun对象
	 */
	public static Xsun me(){
		return XsunHolder.ME ;
	}
	
	public Xsun loadConf(String confPath){
		configLoader.load(confPath);
		return this ;
	}
	public Xsun setConf(String name, String value){
		configLoader.setConf(name, value);
		return this ;
	}
	
	public String getConf(String name){
		return configLoader.getConf(name) ;
	}
	
	public Xsun addRoutes(Routers routes){
		this.routers.addRoute(routes.getRoutes());
		return this ;
	}
	
	/**
	 * 添加路由
	 * @param path 路由名称
	 * @param methodName 对应的的方法名
	 * @param controller 对应的控制器
	 * @return Xsun对象
	 */
	public Xsun addRoute(String path, String methodName, Object controller){
		try {
			Method method = controller.getClass().getMethod(methodName, Request.class, Response.class);
			this.routers.addRoute(path, method, controller);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		return this ;
	}
	
	public Render getRender() {
		return render;
	}

	public void setRender(Render render) {
		this.render = render;
	}

	public Routers getRouters() {
		return routers ;
	}
	
}
